package com.buaa.rental.Service;

import com.buaa.rental.Dao.Home;
import com.buaa.rental.Dao.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class HomeService
{

	@Autowired
	MongoTemplate mongoTemplate;

	public Home addHome(Home home)
	{
		mongoTemplate.insert(home);
		return home;
	}

	public Home findById(long id)
	{
		Query q = new Query(Criteria.where("id").is(id));
		return mongoTemplate.findOne(q, Home.class);
	}

	public void changeStatus(long id, Home.RoomStatus tos)
	{
		Query q1 = new Query(Criteria.where("id").is(id));
		Update u1 = Update.update("roomStatus", tos);
		mongoTemplate.updateFirst(q1, u1, Home.class);
	}

	public List<Home> searchHomes(String pattern)
	{
		Query q = new Query(
				new Criteria().orOperator(Criteria.where("title").regex(".*" + pattern + ".*"),
						Criteria.where("description").regex(".*" + pattern + ".*"),
						Criteria.where("address").regex(".*" + pattern + ".*"),
						Criteria.where("layout").is(pattern),
						Criteria.where("tags").is(pattern)
				));
		q.with(new Sort(Sort.DEFAULT_DIRECTION,"id"));
		List<Home> result = new ArrayList<>(mongoTemplate.find(q, Home.class));
		return result;
	}
}
